<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>多站点结果 - {{ project.projectname }}</title>
{#    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet">#}
    <link href="{{ url_for('static',filename='bootstrap/css/bootstrap.min.css') }}" rel="stylesheet">
{#    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.11.1/font/bootstrap-icons.min.css" rel="stylesheet">#}
    <link href="{{ url_for('static',filename='bootstrap/bootstrap-icons-1.11.1/bootstrap-icons.min.css') }}" rel="stylesheet">
{#    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>#}
    <script src="{{ url_for('static',filename='jquery/jquery-3.7.1.min.js') }}"></script>
{#    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.bundle.min.js"></script>#}
    <script src="{{ url_for('static',filename='bootstrap/js/bootstrap.bundle.min.js') }}"></script>
{#    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>#}
    <script src="{{ url_for('static',filename='chart/chart.min.js') }}"></script>
{#    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>#}
    <script src="{{ url_for('static',filename='xlsx/xlsx.full.min.js') }}"></script>
    <style>
    :root {
        --primary-color: #2E7D32;
        --secondary-color: #81C784;
        --accent-color: #DCEDC8;
        --text-color: #212121;
        --light-text: #757575;
        --light-green: #E8F5E9;
        --dark-green: #1B5E20;
        --amber: #FFD54F;
        --brown: #795548;
        --leaf-green: #66BB6A;
    }

    body {
        background-color: #F8F9FA;
        background-image: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M54.627 0l.83.828-1.415 1.415L51.8 0h2.827zM5.373 0l-.83.828L5.96 2.243 8.2 0H5.374zM48.97 0l3.657 3.657-1.414 1.414L46.143 0h2.828zM11.03 0L7.372 3.657 8.787 5.07 13.857 0H11.03zm32.284 0L49.8 6.485 48.384 7.9l-7.9-7.9h2.83zM16.686 0L10.2 6.485 11.616 7.9l7.9-7.9h-2.83zm20.97 0l9.315 9.314-1.414 1.414L34.828 0h2.83zM22.344 0L13.03 9.314l1.414 1.414L25.172 0h-2.83zM32 0l12.142 12.142-1.414 1.414L30 .828 17.272 13.556l-1.414-1.414L28 0h4zM.284 0l28 28-1.414 1.414L0 2.544V0h.284zM0 5.373l25.456 25.455-1.414 1.415L0 8.2V5.374zm0 5.656l22.627 22.627-1.414 1.414L0 13.86v-2.83zm0 5.656l19.8 19.8-1.415 1.413L0 19.514v-2.83zm0 5.657l16.97 16.97-1.414 1.415L0 25.172v-2.83zM0 28l14.142 14.142-1.414 1.414L0 30.828V28zm0 5.657L11.314 44.97 9.9 46.386l-9.9-9.9v-2.828zm0 5.657L8.485 47.8 7.07 49.212 0 42.143v-2.83zm0 5.657l5.657 5.657-1.414 1.415L0 47.8v-2.83zm0 5.657l2.828 2.83-1.414 1.413L0 53.456v-2.83zM54.627 60L30 35.373 5.373 60H8.2L30 38.2 51.8 60h2.827zm-5.656 0L30 41.03 11.03 60h2.828L30 43.858 46.142 60h2.83zm-5.656 0L30 46.686 16.686 60h2.83L30 49.515 40.485 60h2.83zm-5.657 0L30 52.343 22.344 60h2.83L30 55.172 34.828 60h2.83zM32 60l-2-2-2 2h4zM59.716 0l-28 28 1.414 1.414L60 2.544V0h-.284zM60 5.373L34.544 30.828l1.414 1.415L60 8.2V5.374zm0 5.656L37.373 33.656l1.414 1.414L60 13.86v-2.83zm0 5.656l-19.8 19.8 1.415 1.413L60 19.514v-2.83zm0 5.657l-16.97 16.97 1.414 1.415L60 25.172v-2.83zM60 28L45.858 42.142l1.414 1.414L60 30.828V28zm0 5.657L48.686 44.97l1.415 1.415 9.9-9.9v-2.828zm0 5.657L51.515 47.8l1.414 1.414L60 42.143v-2.83zm0 5.657l-5.657 5.657 1.414 1.415L60 47.8v-2.83zm0 5.657l-2.828 2.83 1.414 1.413L60 53.456v-2.83zM39.9 16.385l1.414-1.414L30 3.658 18.686 14.97l1.415 1.415 9.9-9.9 9.9 9.9zm-2.83 2.828l1.415-1.414L30 9.313 21.515 17.8l1.414 1.413L30 11.8l7.07 7.414v-.002zm-2.827 2.83l1.414-1.416L30 14.97l-5.657 5.657 1.414 1.415L30 17.8l4.243 4.242zm-2.83 2.827l1.415-1.414L30 20.626l-2.828 2.83 1.414 1.414L30 23.456l1.414 1.414zM56.87 59.414L58.284 58 30 29.716 1.716 58l1.414 1.414L30 32.544l26.87 26.87z' fill='%2381c784' fill-opacity='0.07' fill-rule='evenodd'/%3E%3C/svg%3E");
        color: var(--text-color);
        padding: 1.5rem;
        min-height: 100vh;
        font-family: "SF Mono", "JetBrains Mono", "Cascadia Code", Menlo, Consolas, "IBM Plex Mono", "Fira Code", monospace;
    }

    /* 页面标题部分 */
    .page-header {
        margin-bottom: 1.5rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 0.8rem;
        border-bottom: 1px solid rgba(0, 0, 0, 0.07);
    }

    .page-title {
        color: var(--primary-color);
        font-weight: 700;
        font-size: 2rem;
        margin-bottom: 0;
        position: relative;
        padding-left: 2.2rem;
    }

    .page-title::before {
        content: "";
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 1.8rem;
        height: 1.8rem;
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%232E7D32' d='M12 3L1 9L5 11.18V17.18L12 21L19 17.18V11.18L21 10.09V17H23V9L12 3M18.82 9L12 12.72L5.18 9L12 5.28L18.82 9M17 16L12 18.72L7 16V12.27L12 15L17 12.27V16Z'/%3E%3C/svg%3E");
        background-repeat: no-repeat;
        background-size: contain;
    }

    .project-name {
        font-weight: 600;
        color: var(--dark-green);
        background-color: var(--light-green);
        padding: 0.3rem 0.7rem;
        border-radius: 4px;
        margin-left: 0.5rem;
        font-size: 1.3rem;
    }

    .header-actions {
        display: flex;
        gap: 1rem;
    }

    .btn-back {
        background-color: white;
        border-color: rgba(0, 0, 0, 0.1);
        color: var(--light-text);
        padding: 0.6rem 1.2rem;
        border-radius: 8px;
        font-weight: 500;
        transition: all 0.3s ease;
    }

    .btn-back:hover {
        background-color: rgba(0, 0, 0, 0.05);
        color: var(--text-color);
        border-color: rgba(0, 0, 0, 0.2);
    }

    .btn-primary {
        background-color: var(--primary-color);
        border-color: var(--primary-color);
        padding: 0.6rem 1.2rem;
        border-radius: 8px;
        font-weight: 500;
        box-shadow: 0 2px 8px rgba(46, 125, 50, 0.3);
        transition: all 0.3s ease;
    }

    .btn-primary:hover {
        background-color: var(--dark-green);
        border-color: var(--dark-green);
        box-shadow: 0 4px 12px rgba(46, 125, 50, 0.4);
        transform: translateY(-2px);
    }

    .btn-success {
        background-color: var(--leaf-green);
        border-color: var(--leaf-green);
        padding: 0.6rem 1.2rem;
        border-radius: 8px;
        font-weight: 500;
        box-shadow: 0 2px 8px rgba(102, 187, 106, 0.3);
        transition: all 0.3s ease;
    }

    .btn-success:hover {
        background-color: #4CAF50;
        border-color: #4CAF50;
        box-shadow: 0 4px 12px rgba(102, 187, 106, 0.4);
        transform: translateY(-2px);
    }

    /* 参数部分 */
    .parameter-section {
        background-color: white;
        border-radius: 12px;
        box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
        overflow: hidden;
        margin-bottom: 1.5rem;
        position: relative;
    }

    .parameter-section::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 6px;
        background: linear-gradient(90deg, var(--leaf-green), var(--secondary-color));
    }

    .parameter-header {
        padding: 1rem 1.5rem 0;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    }

    .parameter-title {
        font-weight: 600;
        color: var(--primary-color);
        margin-bottom: 0;
        font-size: 1.25rem;
        display: flex;
        align-items: center;
    }

    .parameter-title i {
        margin-right: 0.5rem;
        color: var(--leaf-green);
        font-size: 1.35rem;
    }

    .parameter-subtitle {
        color: var(--light-text);
        font-size: 0.9rem;
        margin-top: 0.5rem;
    }

    .parameter-content {
        padding: 1rem 1.5rem 1.5rem;
    }

    /* 控制面板 */
    .controls {
        padding: 0.8rem 0;
    }

    .input-group-text {
        background-color: var(--light-green);
        color: var(--dark-green);
        border-color: rgba(0, 0, 0, 0.1);
        font-weight: 500;
    }

    .form-select {
        border-color: rgba(0, 0, 0, 0.1);
    }

    .form-select:focus {
        border-color: var(--secondary-color);
        box-shadow: 0 0 0 0.2rem rgba(102, 187, 106, 0.25);
    }

    .action-buttons {
        display: flex;
        gap: 0.8rem;
        justify-content: flex-end;
    }

    /* 图表容器 */
    .chart-container {
        position: relative;
        height: 400px;
        width: 100%;
        background-color: rgba(255, 255, 255, 0.7);
        border-radius: 8px;
        padding: 1rem;
        border: 1px solid rgba(0, 0, 0, 0.05);
    }

    /* 表格样式 */
    .table-container {
        max-height: 500px;
        overflow-y: auto;
        border-radius: 8px;
        border: 1px solid rgba(0, 0, 0, 0.05);
    }

    .table {
        margin-bottom: 0;
    }

    .table th {
        position: sticky;
        top: 0;
        background-color: var(--light-green);
        color: var(--dark-green);
        font-weight: 600;
        z-index: 1;
        text-align: center;
    }

    .table td {
        text-align: center;
        vertical-align: middle;
    }

    .table-striped tbody tr:nth-of-type(odd) {
        background-color: rgba(232, 245, 233, 0.3);
    }

    .table-hover tbody tr:hover {
        background-color: rgba(232, 245, 233, 0.5);
    }

    /* 返回顶部按钮 */
    .back-to-top {
        position: fixed;
        bottom: 2rem;
        right: 2rem;
        width: 3rem;
        height: 3rem;
        border-radius: 50%;
        background-color: var(--primary-color);
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        cursor: pointer;
        opacity: 0;
        transition: opacity 0.3s ease;
        z-index: 1000;
    }

    .back-to-top.visible {
        opacity: 1;
    }

    .back-to-top:hover {
        background-color: var(--dark-green);
        transform: translateY(-3px);
        box-shadow: 0 4px 15px rgba(0,0,0,0.3);
    }

    /* 浮动提示 */
    .floating-alert {
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        z-index: 9999;
        min-width: 300px;
        text-align: center;
        box-shadow: 0 4px 8px rgba(0,0,0,0.2);
    }

    /* 响应式样式 */
    @media (max-width: 768px) {
        .page-title {
            font-size: 1.6rem;
        }

        .project-name {
            display: block;
            margin: 0.5rem 0 0;
            width: fit-content;
        }

        .header-actions {
            flex-direction: column;
            gap: 0.5rem;
        }

        body {
            padding: 1rem;
        }

        .action-buttons {
            justify-content: flex-start;
            margin-top: 0.8rem;
        }

        .chart-container {
            height: 300px;
        }
    }

    /* 表格样式 */
    .table-container {
        max-height: 500px;
        overflow-y: auto;
        border-radius: 8px;
        border: 1px solid rgba(0, 0, 0, 0.05);
    }

    .table {
        margin-bottom: 0;
        table-layout: fixed; /* 固定表格布局 */
        width: 100%;
    }

    .table th {
        position: sticky;
        top: 0;
        background-color: var(--light-green);
        color: var(--dark-green);
        font-weight: 600;
        z-index: 1;
        text-align: center;
        white-space: nowrap; /* 防止换行 */
        padding: 0.5rem 0.75rem;
        min-width: 100px; /* 最小宽度 */
    }

    .table td {
        text-align: center;
        vertical-align: middle;
        white-space: nowrap; /* 防止换行 */
        padding: 0.5rem 0.75rem;
    }

    .table-striped tbody tr:nth-of-type(odd) {
        background-color: rgba(232, 245, 233, 0.3);
    }

    .table-hover tbody tr:hover {
        background-color: rgba(232, 245, 233, 0.5);
    }

    /* 增加表格的滚动条样式 */
    .table-responsive {
        overflow-x: auto;
        scrollbar-width: thin;
        scrollbar-color: var(--primary-color) #f0f0f0;
    }

    .table-responsive::-webkit-scrollbar {
        height: 8px;
        width: 8px;
    }

    .table-responsive::-webkit-scrollbar-track {
        background: #f0f0f0;
        border-radius: 4px;
    }

    .table-responsive::-webkit-scrollbar-thumb {
        background-color: var(--primary-color);
        border-radius: 4px;
    }

    /* 添加到CSS样式部分 */
    .checkbox-container {
        display: flex;
        flex-wrap: wrap;
        max-height: 130px;
        overflow-y: hidden;
        transition: max-height 0.3s ease;
    }

    .checkbox-container.expanded {
        max-height: 500px;
    }

    .checkbox-toggle {
        cursor: pointer;
        color: var(--primary-color);
        display: inline-flex;
        align-items: center;
        font-weight: 500;
        margin-top: 0.5rem;
    }

    .checkbox-toggle i {
        margin-right: 0.3rem;
        transition: transform 0.3s ease;
    }

    .checkbox-toggle.expanded i {
        transform: rotate(180deg);
    }

    .form-check {
        flex: 0 0 auto;
        width: 20%; /* 每行显示5个 */
        margin-bottom: 0.5rem;
    }

    @media (max-width: 1200px) {
        .form-check {
            width: 25%; /* 在中等屏幕上每行显示4个 */
        }
    }

    @media (max-width: 992px) {
        .form-check {
            width: 33.33%; /* 在小屏幕上每行显示3个 */
        }
    }

    @media (max-width: 768px) {
        .form-check {
            width: 50%; /* 在更小的屏幕上每行显示2个 */
        }
    }


    /* 新增粘性控制面板样式 */
    .sticky-controls {
        position: sticky;
        top: 15px;
        z-index: 100;
        background-color: white;
        border-radius: 8px;
        padding: 10px 15px;
        box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
        margin-bottom: 15px;
        border: 1px solid rgba(0, 0, 0, 0.05);
    }

    /* 更紧凑的复选框布局 */
    .form-check {
        flex: 0 0 auto;
        width: 16.666%; /* 改为每行6个 */
        margin-bottom: 0.3rem;
        padding-left: 1.5rem; /* 减小左边距 */
    }

    .form-check-label {
        font-size: 0.85rem; /* 缩小字体 */
        white-space: nowrap; /* 防止换行 */
        overflow: hidden;
        text-overflow: ellipsis; /* 过长时显示省略号 */
        display: block;
    }

    .form-check-input {
        margin-top: 0.2rem; /* 微调复选框位置 */
        margin-left: -1.5rem; /* 配合减小的左边距 */
    }

    /* 复选框容器样式调整 */
    .checkbox-container {
        max-height: 100px; /* 减小初始高度 */
    }

    /* 响应式调整 */
    @media (max-width: 1200px) {
        .form-check {
            width: 20%; /* 在中等屏幕上每行显示5个 */
        }
    }

    @media (max-width: 992px) {
        .form-check {
            width: 25%; /* 在小屏幕上每行显示4个 */
        }
    }

    @media (max-width: 768px) {
        .form-check {
            width: 33.33%; /* 在更小的屏幕上每行显示3个 */
        }

        /* 手机版上固定在底部 */
        .sticky-controls {
            position: fixed;
            top: auto;
            bottom: 0;
            left: 0;
            right: 0;
            width: 100%;
            border-radius: 8px 8px 0 0;
            z-index: 1001; /* 确保在返回顶部按钮之上 */
            padding: 8px 10px;
            transform: translateY(calc(100% - 40px)); /* 初始只显示顶部 */
            transition: transform 0.3s ease;
        }

        .sticky-controls.expanded {
            transform: translateY(0); /* 展开时完全显示 */
        }

        /* 添加拖动条指示器 */
        .sticky-controls::before {
            content: "";
            position: absolute;
            top: 5px;
            left: 50%;
            transform: translateX(-50%);
            width: 40px;
            height: 4px;
            background-color: rgba(0, 0, 0, 0.1);
            border-radius: 2px;
        }
    }

    .parameter-header {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        align-items: center;
    }

    .parameter-title {
        margin-right: auto;
    }

    .parameter-subtitle {
        width: 100%;
        margin-top: 0.5rem;
        margin-bottom: 0.5rem;
    }

    .download-site-btn {
        margin-left: 1rem;
    }

    .parameter-header {
        padding: 1rem 1.5rem 0;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    }

    .parameter-title {
        font-weight: 600;
        color: var(--primary-color);
        margin-bottom: 0;
        font-size: 1.25rem;
        display: flex;
        align-items: center;
    }

    .download-site-btn {
        padding: 0.3rem 0.8rem;
        font-size: 0.85rem;
        display: flex;
        align-items: center;
        gap: 0.3rem;
        position: relative;
        top:20px;
    }

    .download-site-btn i {
        font-size: 1rem;
    }

    /* 响应式调整 */
    @media (max-width: 576px) {
        .download-site-btn {
            padding: 0.25rem 0.6rem;
            font-size: 0.8rem;
        }

        .parameter-title {
            font-size: 1.1rem;
        }
    }

    .charts-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr); /* 默认2列布局 */
        gap: 15px;
        width: 100%;
        min-height: 200px;
    }

    .chart-item {
        background-color: rgba(255, 255, 255, 0.7);
        border-radius: 8px;
        padding: 1rem;
        border: 1px solid rgba(0, 0, 0, 0.05);
        height: 250px;
        position: relative;
    }

    @media (min-width: 992px) {
        .charts-grid {
            grid-template-columns: repeat(3, 1fr); /* 在大屏幕上使用3列 */
        }
    }

    @media (max-width: 768px) {
        .charts-grid {
            grid-template-columns: repeat(1, 1fr); /* 在小屏幕上使用1列 */
        }
    }
    </style>
</head>
<body>
    <div class="container-fluid p-0">
        <!-- 页面标题和返回按钮 -->
        <div class="page-header">
            <h1 class="page-title">多站点结果<span class="project-name">{{ project.projectname }}</span></h1>
            <div class="header-actions">
                <a href="{{ url_for('calc.EnterMultiSite', projectId=project.id) }}" class="btn btn-back">
                    <i class="bi bi-arrow-left"></i> 返回编辑
                </a>
                <button type="button" id="downloadAllBtn" class="btn btn-primary">
                    <i class="bi bi-download"></i> 下载全部数据
                </button>
            </div>
        </div>

        <!-- 内容区域 -->
        {% for site_name, data in data_output.items() %}
        <div class="parameter-section site-section" id="site-{{ loop.index }}">
            <div class="parameter-header">
                <h2 class="parameter-title">
                    <i class="bi bi-pin-map"></i> {{ site_name }}
                </h2>
                <button type="button" class="btn btn-success btn-sm download-site-btn" data-site="{{ site_name }}">
                    <i class="bi bi-file-earmark-arrow-down"></i> 下载此站点数据
                </button>
                <p class="parameter-subtitle">林分生长模拟结果</p>
            </div>
            <div class="parameter-content">
                <!-- 新的固定控制面板 -->
                <div class="sticky-controls" id="controls-{{ site_name }}">
                    <div class="form-group mb-0">
                        <label class="mb-1 d-flex align-items-center justify-content-between">
                            <div class="d-flex align-items-center">
                                <i class="bi bi-graph-up me-2 text-success"></i> 选择变量（最多6个）
                            </div>
                            <div class="checkbox-toggle" id="toggle-{{ site_name }}">
                                <i class="bi bi-chevron-down"></i> 展开
                            </div>
                        </label>
                        <div class="checkbox-container" id="var-checkboxes-{{ site_name }}">
                            {% for var in output_vars %}
                                {% if var != 'Time' %}
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" value="{{ var }}"
                                               id="check-{{ site_name }}-{{ var }}" {% if loop.index0 < 6 %}checked{% endif %}>
                                        <label class="form-check-label" for="check-{{ site_name }}-{{ var }}">
                                            {{ var }}
                                            {% if var in ['WF', 'WR', 'WS', 'StandVol', 'TotalW'] %}(t/ha)
                                            {% elif var == 'LAI' %}{% elif var == 'StemNo' %}(trees/ha)
                                            {% elif var == 'NPP' %}(t/ha/yr){% endif %}
                                        </label>
                                    </div>
                                {% endif %}
                            {% endfor %}
                        </div>
                    </div>
                </div>

                <!-- 图表网格容器 -->
                <div class="charts-grid" id="charts-grid-{{ site_name }}">
                    <!-- Individual chart containers will be dynamically added here -->
                </div>

                <!-- 数据表格 -->
                <div class="table-container mt-4">
                    <table id="site-{{ site_name }}" class="table table-bordered table-striped table-hover">
                        <thead>
                            <tr>
                                <th>时间 (年-月)</th>
                                {% for var in output_vars %}
                                    {% if var != 'Time' %}
                                        <th>{{ var }}
                                            {% if var in ['WF', 'WR', 'WS', 'StandVol', 'TotalW'] %}(t/ha)
                                            {% elif var == 'LAI' %}{% elif var == 'StemNo' %}(trees/ha)
                                            {% elif var == 'NPP' %}(t/ha/yr){% endif %}
                                        </th>
                                    {% endif %}
                                {% endfor %}
                            </tr>
                        </thead>
                        <tbody>
                            {% for i in range(data['Time']|length) %}
                            <tr>
                                <td>{{ data['Time'][i] }}</td>
                                {% for var in output_vars %}
                                    {% if var != 'Time' %}
                                        <td>{{ data[var][i]|round(2) }}</td>
                                    {% endif %}
                                {% endfor %}
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        {% endfor %}

        <!-- 返回顶部按钮 -->
        <div id="backToTop" class="back-to-top">
            <i class="bi bi-arrow-up"></i>
        </div>
    </div>

    <!-- Script部分将在后续添加 -->
    <script>
        // 单位映射
        const units = {
            'WF': 't/ha', 'WS': 't/ha', 'WR': 't/ha', 'StandVol': 'm³/ha', 'TotalW': 't/ha',
            'LAI': '', 'StemNo': 'trees/ha', 'NPP': 't/ha/yr'
        };

        // 图表实例存储
        const charts = {};

        // 颜色映射
        const colorPalette = [
            '#2E7D32', // 深绿
            '#1976D2', // 蓝色
            '#E64A19', // 橙红
            '#7B1FA2', // 紫色
            '#FFA000', // 琥珀
            '#00897B', // 蓝绿
            '#558B2F', // 橄榄绿
            '#6D4C41', // 棕色
            '#5D4037', // 深棕
            '#F57F17'  // 黄色
        ];

        // 修复updateTableColumns函数
        function updateTableColumns(siteName) {
            const checkboxContainer = document.getElementById('var-checkboxes-' + siteName);
            const checkboxes = checkboxContainer.querySelectorAll('input[type="checkbox"]');

            // 修复表格选择器 - 使用正确的ID选择器格式
            const tableContainer = document.getElementById('site-' + siteName);

            if (!tableContainer) {
                console.error('未找到表格容器:', 'site-' + siteName);
                return;
            }

            // 获取所有选中的变量
            const selectedVars = Array.from(checkboxes)
                .filter(cb => cb.checked)
                .map(cb => cb.value);

            // 获取表头和所有行
            const headerRow = tableContainer.querySelector('thead tr');
            const bodyRows = tableContainer.querySelectorAll('tbody tr');

            if (!headerRow || !bodyRows.length) {
                console.error('未找到表头或表格行');
                return;
            }

            // 获取表格中所有列（除第一列日期外）
            const headerCells = headerRow.querySelectorAll('th');

            // 遍历表头单元格（从第二列开始，第一列是日期）
            for (let i = 1; i < headerCells.length; i++) {
                const th = headerCells[i];
                // 改进变量名提取逻辑
                const varName = th.textContent.trim().split(/[\s(]/)[0].trim();

                // 检查这个变量是否被选中
                const isSelected = selectedVars.includes(varName);

                // 设置表头单元格可见性
                th.style.display = isSelected ? '' : 'none';

                // 设置每行相应列的可见性
                bodyRows.forEach(row => {
                    const td = row.querySelectorAll('td')[i];
                    if (td) {
                        td.style.display = isSelected ? '' : 'none';
                    }
                });
            }
        }

        // 在初始化时确保表格列可见性与复选框状态一致
        function initializeCheckboxes(siteName) {
            const checkboxContainer = document.getElementById('var-checkboxes-' + siteName);
            const checkboxToggle = document.getElementById('toggle-' + siteName);
            const checkboxes = checkboxContainer.querySelectorAll('input[type="checkbox"]');
            const stickyControl = document.getElementById('controls-' + siteName);

            // 初始化复选框折叠/展开功能
            checkboxToggle.addEventListener('click', function() {
                checkboxContainer.classList.toggle('expanded');
                checkboxToggle.classList.toggle('expanded');

                if (checkboxContainer.classList.contains('expanded')) {
                    checkboxToggle.innerHTML = '<i class="bi bi-chevron-up"></i> 收起';
                } else {
                    checkboxToggle.innerHTML = '<i class="bi bi-chevron-down"></i> 展开';
                }
            });

            // 移动设备处理
            if (window.innerWidth <= 768) {
                // 点击拖动条展开/收起
                stickyControl.addEventListener('click', function(e) {
                    // 仅当点击的是拖动条区域时
                    if (e.target === stickyControl || e.clientY < stickyControl.offsetTop + 40) {
                        stickyControl.classList.toggle('expanded');
                    }
                });
            }

            // 如果复选框超过6个，只保留前6个选中
            if (checkboxes.length > 6) {
                for (let i = 0; i < checkboxes.length; i++) {
                    if (i < 6) {
                        checkboxes[i].checked = true;
                    } else {
                        checkboxes[i].checked = false;
                    }
                }
            }

            // 为每个复选框添加点击事件
            checkboxes.forEach(checkbox => {
                checkbox.addEventListener('change', function() {
                    // 如果选中数量超过6个，则取消当前选中
                    const checkedBoxes = checkboxContainer.querySelectorAll('input[type="checkbox"]:checked');
                    if (checkedBoxes.length > 6 && checkbox.checked) {
                        checkbox.checked = false;
                        showAlert('最多只能选择6个变量', 'warning');
                        return;
                    }

                    // 至少保留一个选中
                    if (checkedBoxes.length === 0) {
                        checkbox.checked = true;
                        showAlert('请至少选择一个变量', 'warning');
                        return;
                    }

                    // 更新图表
                    updateChart(siteName);

                    // 更新表格可见列
                    updateTableColumns(siteName);
                });
            });

            // 初始化时更新表格列显示状态
            console.log('正在初始化表格可见列：', siteName);
            updateTableColumns(siteName);
        }

        // 处理粘性控制面板在滚动时的行为
        function handleStickyControls() {
            // 获取所有站点区域
            const siteSections = document.querySelectorAll('.site-section');

            siteSections.forEach((section, index) => {
                const sectionId = section.id;
                const siteName = sectionId.replace('site-', '');
                const controlPanel = document.getElementById('controls-' + siteName);

                if (!controlPanel) return;

                // 计算该区域是否在视口中
                const rect = section.getBoundingClientRect();
                const isInView = (
                    rect.top <= 200 && // 区域顶部在视口顶部以下200px
                    rect.bottom >= 200 // 区域底部在视口顶部以上
                );

                // 如果在桌面版上
                if (window.innerWidth > 768) {
                    // 仅当区域在视图中时才显示对应的控制面板
                    if (isInView) {
                        controlPanel.style.display = '';
                    } else {
                        controlPanel.style.display = 'none';
                    }
                }
            });
        }

        // 初始化站点下载按钮
        function initSiteDownloadButtons() {
            // 获取所有站点下载按钮
            const downloadButtons = document.querySelectorAll('.download-site-btn');

            // 为每个按钮添加点击事件
            downloadButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const siteName = this.getAttribute('data-site');
                    downloadSiteData(siteName);
                });
            });
        }

        // 下载单个站点数据
        function downloadSiteData(siteName) {
            try {
                // 显示加载提示
                showAlert(`正在准备下载 ${siteName} 的数据...`, 'info');

                // 获取站点数据
                const siteData = {{ data_output|tojson }}[siteName];
                const outputVars = Object.keys(siteData);

                // 获取当前表格显示的列
                const tableId = 'site-' + siteName;
                const table = document.getElementById(tableId);
                const visibleColumns = [];

                // 获取表头中可见的列（除了第一列"日期"外）
                const headerCells = table.querySelectorAll('thead th');
                headerCells.forEach((th, index) => {
                    if (index > 0 && th.style.display !== 'none') {
                        // 提取变量名（清除单位标记）
                        const varName = th.textContent.trim().split(/[\s(]/)[0].trim();
                        visibleColumns.push(varName);
                    }
                });

                // 准备CSV内容
                let csvContent = "时间 (年-月)";
                visibleColumns.forEach(varName => {
                    // 添加列标题（带单位）
                    if (['WF', 'WR', 'WS', 'StandVol', 'TotalW'].includes(varName)) {
                        csvContent += `,${varName} (t/ha)`;
                    } else if (varName === 'StemNo') {
                        csvContent += `,${varName} (trees/ha)`;
                    } else if (varName === 'NPP') {
                        csvContent += `,${varName} (t/ha/yr)`;
                    } else {
                        csvContent += `,${varName}`;
                    }
                });
                csvContent += "\n";

                // 添加数据行
                for (let i = 0; i < siteData['Time'].length; i++) {
                    csvContent += siteData['Time'][i];
                    visibleColumns.forEach(varName => {
                        // 保留两位小数
                        csvContent += `,${Number(siteData[varName][i]).toFixed(2)}`;
                    });
                    csvContent += "\n";
                }

                // 创建Blob对象
                const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });

                // 创建下载链接
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);

                // 设置链接属性
                link.setAttribute('href', url);
                link.setAttribute('download', `${siteName}_林分生长数据_${new Date().toISOString().split('T')[0]}.csv`);
                link.style.display = 'none';

                // 添加到文档并触发点击
                document.body.appendChild(link);
                link.click();

                // 清理
                document.body.removeChild(link);
                URL.revokeObjectURL(url);

                // 显示成功提示
                showAlert(`${siteName} 的数据已成功下载`, 'success');

            } catch (error) {
                console.error(`下载 ${siteName} 数据时出错:`, error);
                showAlert(`下载数据时出错，请稍后再试`, 'danger');
            }
        }

        // 页面加载完成后执行初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化所有站点图表
            {% for site_name, data in data_output.items() %}
            initializeCheckboxes('{{ site_name }}');
            initializeChart('{{ site_name }}', {{ data|tojson }});
            {% endfor %}

            // 初始化返回顶部按钮
            initBackToTop();

            // 初始化全局下载按钮
            initDownloadAllBtn();

            // 监听滚动事件，处理控制面板的显示/隐藏
            window.addEventListener('scroll', handleStickyControls);

            // 初始调用一次以设置正确状态
            handleStickyControls();

            // 初始化站点下载按钮
            initSiteDownloadButtons();
        });

        // 初始化单个站点图表
        // 初始化单个站点的图表网格
        function initializeChart(siteName, data) {
            const chartsGrid = document.getElementById('charts-grid-' + siteName);
            const checkboxContainer = document.getElementById('var-checkboxes-' + siteName);
            const checkboxes = checkboxContainer.querySelectorAll('input[type="checkbox"]:checked');

            // 清空现有图表
            chartsGrid.innerHTML = '';

            // 创建图表对象数组（如果不存在）
            if (!charts[siteName]) {
                charts[siteName] = {};
            }

            // 为每个选中的变量创建一个图表
            checkboxes.forEach((checkbox, index) => {
                const varName = checkbox.value;

                // 创建图表容器
                const chartItem = document.createElement('div');
                chartItem.className = 'chart-item';
                chartItem.id = `chart-item-${siteName}-${varName}`;

                // 创建画布元素
                const canvas = document.createElement('canvas');
                canvas.id = `chart-${siteName}-${varName}`;
                chartItem.appendChild(canvas);

                // 添加到网格
                chartsGrid.appendChild(chartItem);

                // 获取上下文并创建图表
                const ctx = canvas.getContext('2d');

                // 使用对应的颜色
                const colorIndex = index % colorPalette.length;

                // 确定是否使用第二Y轴
                const useSecondAxis = varName === 'StemNo';

                // 创建数据集
                const dataset = {
                    label: varName + (units[varName] ? ` (${units[varName]})` : ''),
                    data: data[varName],
                    borderColor: colorPalette[colorIndex],
                    backgroundColor: colorPalette[colorIndex] + '33', // 添加透明度
                    fill: false,
                    tension: 0.2,
                    pointRadius: 3,
                    pointHoverRadius: 5,
                    borderWidth: 2,
                };

                // 创建图表
                charts[siteName][varName] = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: data['Time'],  // 使用 Time 作为横轴标签
                        datasets: [dataset]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        interaction: {
                            mode: 'index',
                            intersect: false,
                        },
                        scales: {
                            x: {
                                title: {
                                    display: true,
                                    text: '时间 (年-月)',
                                    font: {
                                        weight: 'bold',
                                        size: 10
                                    }
                                },
                                ticks: {
                                    maxRotation: 45,
                                    minRotation: 45,
                                    autoSkip: true,
                                    maxTicksLimit: 10,
                                    font: {
                                        size: 9
                                    }
                                },
                                grid: {
                                    color: 'rgba(0, 0, 0, 0.05)'
                                }
                            },
                            y: {
                                title: {
                                    display: true,
                                    text: useSecondAxis ? 'StemNo (trees/ha)' : units[varName] || varName,
                                    font: {
                                        weight: 'bold',
                                        size: 10
                                    }
                                },
                                beginAtZero: true,
                                grid: {
                                    color: 'rgba(0, 0, 0, 0.05)'
                                },
                                ticks: {
                                    font: {
                                        size: 9
                                    }
                                }
                            }
                        },
                        plugins: {
                            legend: {
                                display: false // 单个变量图表不需要图例
                            },
                            title: {
                                display: true,
                                text: varName + (units[varName] ? ` (${units[varName]})` : ''),
                                font: {
                                    size: 14,
                                    weight: 'bold'
                                },
                                padding: {
                                    top: 5,
                                    bottom: 10
                                }
                            },
                            tooltip: {
                                backgroundColor: 'rgba(255, 255, 255, 0.9)',
                                titleColor: '#2E7D32',
                                bodyColor: '#212121',
                                borderColor: 'rgba(46, 125, 50, 0.2)',
                                borderWidth: 1,
                                boxPadding: 5,
                                usePointStyle: true,
                                callbacks: {
                                    label: function(context) {
                                        let label = '';
                                        if (context.parsed.y !== null) {
                                            label += context.parsed.y.toFixed(2);
                                            if (units[varName]) {
                                                label += ` ${units[varName]}`;
                                            }
                                        }
                                        return label;
                                    }
                                }
                            }
                        },
                        animation: {
                            duration: 800,
                            easing: 'easeOutQuart'
                        }
                    }
                });
            });

            // 调整网格容器高度
            adjustGridHeight(siteName);
        }
        function adjustGridHeight(siteName) {
            const chartsGrid = document.getElementById('charts-grid-' + siteName);
            const chartItems = chartsGrid.querySelectorAll('.chart-item');

            if (chartItems.length === 0) return;

            // 计算行数（基于当前的网格列数）
            let columnsCount = 2; // 默认值

            // 根据当前视口宽度确定列数
            if (window.innerWidth >= 992) {
                columnsCount = 3;
            } else if (window.innerWidth <= 768) {
                columnsCount = 1;
            }

            // 计算需要多少行
            const rowsCount = Math.ceil(chartItems.length / columnsCount);

            // 设置网格容器的高度（每行高度为单个图表高度+间距）
            // 250px是单个图表高度，15px是间距
            const gridHeight = rowsCount * (250 + 15) - 15;
            chartsGrid.style.height = `${gridHeight}px`;
        }
        // 更新图表
        function updateChart(siteName) {
            const data = {{ data_output|tojson }}[siteName];
            const checkboxContainer = document.getElementById('var-checkboxes-' + siteName);
            const checkboxes = checkboxContainer.querySelectorAll('input[type="checkbox"]');

            // 获取选中和未选中的变量
            const selectedVars = [];
            const unselectedVars = [];

            checkboxes.forEach(checkbox => {
                if (checkbox.checked) {
                    selectedVars.push(checkbox.value);
                } else {
                    unselectedVars.push(checkbox.value);
                }
            });

            // 检查是否至少选择了一个变量
            if (selectedVars.length === 0) {
                showAlert('请至少选择一个变量进行展示', 'warning');
                return;
            }

            // 销毁未选中变量的图表
            unselectedVars.forEach(varName => {
                if (charts[siteName] && charts[siteName][varName]) {
                    charts[siteName][varName].destroy();
                    delete charts[siteName][varName];

                    const chartItem = document.getElementById(`chart-item-${siteName}-${varName}`);
                    if (chartItem && chartItem.parentNode) {
                        chartItem.parentNode.removeChild(chartItem);
                    }
                }
            });

            // 为新选中的变量创建图表
            const chartsGrid = document.getElementById('charts-grid-' + siteName);

            selectedVars.forEach((varName, index) => {
                // 检查是否已经存在此变量的图表
                if (!charts[siteName] || !charts[siteName][varName]) {
                    // 创建新的图表容器
                    const chartItem = document.createElement('div');
                    chartItem.className = 'chart-item';
                    chartItem.id = `chart-item-${siteName}-${varName}`;

                    // 创建画布元素
                    const canvas = document.createElement('canvas');
                    canvas.id = `chart-${siteName}-${varName}`;
                    chartItem.appendChild(canvas);

                    // 添加到网格
                    chartsGrid.appendChild(chartItem);

                    // 获取上下文并创建图表
                    const ctx = canvas.getContext('2d');

                    // 使用对应的颜色
                    const colorIndex = index % colorPalette.length;

                    // 确定是否使用第二Y轴
                    const useSecondAxis = varName === 'StemNo';

                    // 创建数据集
                    const dataset = {
                        label: varName + (units[varName] ? ` (${units[varName]})` : ''),
                        data: data[varName],
                        borderColor: colorPalette[colorIndex],
                        backgroundColor: colorPalette[colorIndex] + '33', // 添加透明度
                        fill: false,
                        tension: 0.2,
                        pointRadius: 3,
                        pointHoverRadius: 5,
                        borderWidth: 2,
                    };

                    // 创建图表
                    if (!charts[siteName]) {
                        charts[siteName] = {};
                    }

                    charts[siteName][varName] = new Chart(ctx, {
                        type: 'line',
                        data: {
                            labels: data['Time'],  // 使用 Time 作为横轴标签
                            datasets: [dataset]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            interaction: {
                                mode: 'index',
                                intersect: false,
                            },
                            scales: {
                                x: {
                                    title: {
                                        display: true,
                                        text: '时间 (年-月)',
                                        font: {
                                            weight: 'bold',
                                            size: 10
                                        }
                                    },
                                    ticks: {
                                        maxRotation: 45,
                                        minRotation: 45,
                                        autoSkip: true,
                                        maxTicksLimit: 10,
                                        font: {
                                            size: 9
                                        }
                                    },
                                    grid: {
                                        color: 'rgba(0, 0, 0, 0.05)'
                                    }
                                },
                                y: {
                                    title: {
                                        display: true,
                                        text: useSecondAxis ? 'StemNo (trees/ha)' : units[varName] || varName,
                                        font: {
                                            weight: 'bold',
                                            size: 10
                                        }
                                    },
                                    beginAtZero: true,
                                    grid: {
                                        color: 'rgba(0, 0, 0, 0.05)'
                                    },
                                    ticks: {
                                        font: {
                                            size: 9
                                        }
                                    }
                                }
                            },
                            plugins: {
                                legend: {
                                    display: false // 单个变量图表不需要图例
                                },
                                title: {
                                    display: true,
                                    text: varName + (units[varName] ? ` (${units[varName]})` : ''),
                                    font: {
                                        size: 14,
                                        weight: 'bold'
                                    },
                                    padding: {
                                        top: 5,
                                        bottom: 10
                                    }
                                },
                                tooltip: {
                                    backgroundColor: 'rgba(255, 255, 255, 0.9)',
                                    titleColor: '#2E7D32',
                                    bodyColor: '#212121',
                                    borderColor: 'rgba(46, 125, 50, 0.2)',
                                    borderWidth: 1,
                                    boxPadding: 5,
                                    usePointStyle: true,
                                    callbacks: {
                                        label: function(context) {
                                            let label = '';
                                            if (context.parsed.y !== null) {
                                                label += context.parsed.y.toFixed(2);
                                                if (units[varName]) {
                                                    label += ` ${units[varName]}`;
                                                }
                                            }
                                            return label;
                                        }
                                    }
                                }
                            },
                            animation: {
                                duration: 800,
                                easing: 'easeOutQuart'
                            }
                        }
                    });
                }
            });

            // 调整网格容器高度
            adjustGridHeight(siteName);
        }

        // 初始化返回顶部按钮
        function initBackToTop() {
            const backToTopBtn = document.getElementById('backToTop');

            // 监听滚动事件
            window.addEventListener('scroll', function() {
                if (window.scrollY > 300) {
                    backToTopBtn.classList.add('visible');
                } else {
                    backToTopBtn.classList.remove('visible');
                }
            });

            // 点击返回顶部
            backToTopBtn.addEventListener('click', function() {
                window.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            });
        }

        // 初始化全局下载按钮
        function initDownloadAllBtn() {
            const downloadBtn = document.getElementById('downloadAllBtn');

            downloadBtn.addEventListener('click', function() {
                // 显示加载中提示
                showAlert('正在准备下载数据...', 'info');

                // 使用setTimeout让UI有时间更新
                setTimeout(function() {
                    try {
                        // 获取所有站点数据
                        const allData = {{ data_output|tojson }};
                        const siteNames = Object.keys(allData);

                        // 创建工作簿
                        const wb = XLSX.utils.book_new();

                        // 为每个站点创建工作表
                        siteNames.forEach(siteName => {
                            const siteData = allData[siteName];
                            const outputVars = Object.keys(siteData);

                            // 准备数据：转换为行数据格式
                            const rows = [];

                            // 添加表头行
                            const headerRow = ['时间 (年-月)'];
                            outputVars.forEach(varName => {
                                if (varName !== 'Time') {
                                    let header = varName;
                                    // 添加单位
                                    if (['WF', 'WR', 'WS', 'StandVol', 'TotalW'].includes(varName)) {
                                        header += ' (t/ha)';
                                    } else if (varName === 'StemNo') {
                                        header += ' (trees/ha)';
                                    } else if (varName === 'NPP') {
                                        header += ' (t/ha/yr)';
                                    }
                                    headerRow.push(header);
                                }
                            });
                            rows.push(headerRow);

                            // 添加数据行
                            for (let i = 0; i < siteData['Time'].length; i++) {
                                const dataRow = [siteData['Time'][i]];
                                outputVars.forEach(varName => {
                                    if (varName !== 'Time') {
                                        // 保留两位小数
                                        dataRow.push(Number(siteData[varName][i]).toFixed(2));
                                    }
                                });
                                rows.push(dataRow);
                            }

                            // 创建工作表
                            const ws = XLSX.utils.aoa_to_sheet(rows);

                            // 添加到工作簿，使用站点名作为sheet名
                            // 处理sheet名长度限制(最大31字符)和无效字符
                            let sheetName = siteName.substring(0, 31)
                                .replace(/[*?:/\\[\]]/g, '_'); // 替换Excel不允许的特殊字符

                            XLSX.utils.book_append_sheet(wb, ws, sheetName);
                        });

                        // 生成Excel文件并下载
                        const fileName = '林分生长模拟结果_' + new Date().toISOString().split('T')[0] + '.xlsx';
                        XLSX.writeFile(wb, fileName);

                        // 显示成功提示
                        showAlert('数据已成功下载', 'success');

                    } catch (error) {
                        console.error('下载数据时出错:', error);
                        showAlert('下载数据时出错，请稍后再试', 'danger');
                    }
                }, 100);
            });
        }

        // 显示浮动提示
        function showAlert(message, type = 'success') {
            // 移除可能已经存在的提示
            const existingAlerts = document.querySelectorAll('.floating-alert');
            existingAlerts.forEach(alert => {
                document.body.removeChild(alert);
            });

            // 创建新提示
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} floating-alert`;
            alertDiv.textContent = message;
            document.body.appendChild(alertDiv);

            // 自动消失
            setTimeout(function() {
                alertDiv.style.opacity = '0';
                setTimeout(function() {
                    if (alertDiv.parentNode) {
                        document.body.removeChild(alertDiv);
                    }
                }, 300);
            }, 2000);
        }

        // 响应式处理
        window.addEventListener('resize', function() {
            // 遍历所有站点，调整网格高度
            {% for site_name, data in data_output.items() %}
            adjustGridHeight('{{ site_name }}');
            {% endfor %}

            // 重新调整所有图表大小
            for (const siteName in charts) {
                if (charts.hasOwnProperty(siteName)) {
                    for (const varName in charts[siteName]) {
                        if (charts[siteName].hasOwnProperty(varName)) {
                            charts[siteName][varName].resize();
                        }
                    }
                }
            }
        });

    </script>
</body>
</html>